package com.intelligence.service.impl;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligence.common.system.AuthContextUtil;
import com.intelligence.entity.pojo.SysRoleUser;
import com.intelligence.entity.vo.SysUserVo;
import com.intelligence.mapper.SysRoleUserMapper;
import com.intelligence.mapper.SysUserMapper;
import com.intelligence.entity.pojo.SysUser;
import com.intelligence.entity.model.LoginModel;
import com.intelligence.entity.model.TokenModel;
import com.intelligence.entity.result.Result;
import com.intelligence.entity.result.ResultCodeEnum;
import com.intelligence.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @description 针对表【sys_user】的数据库操作Service实现
 * @createDate 2024-05-15 19:38:31
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Result<TokenModel> login(LoginModel loginModel) {
        //先判断验证码
        String s = redisTemplate.opsForValue().get("user:login:validatecode:" + loginModel.getCodeKey());
        if (!loginModel.getCaptcha().equalsIgnoreCase(s)) {
            return Result.build(null, ResultCodeEnum.CAPTCHA_ERROR);
        }

        //根据用户名查询出用户信息中的salt
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("username", loginModel.getUserName());
        SysUser sysUser = this.sysUserMapper.selectOne(sysUserQueryWrapper);
        //根据salt与用户输入的密码进行md5加密，与数据库中的password进行比较
        String password = loginModel.getPassword() + sysUser.getSalt();
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUserQueryWrapper.eq("password", pwd);
        sysUser = this.sysUserMapper.selectOne(sysUserQueryWrapper);
        if (sysUser == null) {
            return Result.build(null, ResultCodeEnum.LOGIN_ERROR);
        }
        sysUserQueryWrapper.eq("status", 1);
        sysUser = this.sysUserMapper.selectOne(sysUserQueryWrapper);
        if (sysUser == null) {
            return Result.build(null, ResultCodeEnum.ACCOUNT_STOP);
        }

        String token = UUID.randomUUID().toString().replace("-", "");
        log.info("token------->{}", token);
        redisTemplate.opsForValue().set("user:login" + token, JSON.toJSONString(sysUser), 30, TimeUnit.MINUTES);
        TokenModel tokenModel = new TokenModel();
        tokenModel.setToken(token);
        tokenModel.setRefreshToken("");
        AuthContextUtil.set(sysUser);
        return Result.build(tokenModel, ResultCodeEnum.SUCCESS);
    }

    @Override
    public void logout(String token) {
        AuthContextUtil.remove();
        redisTemplate.delete("user:login:" + token);
    }

    @Override
    public Page<SysUserVo> selectAllUsersAndRole(Integer offset, Integer pageSize, Integer roleId) {
        Page<SysUserVo> sysUserList = this.sysUserMapper.selectAllUsersAndRole(new Page<>(offset, pageSize), roleId);
        return sysUserList;
    }

    @Override
    public int alertTheStatus(Integer id) {
        return this.sysUserMapper.alertTheStatus(id);

    }

    @Override
    public void saveNewUser(SysUser sysUser) {
        if (null==sysUser.getId()){
            //新增
            sysUser.setSalt("qjbz");
            sysUser.setCreatetime(new Date());
            sysUser.setUpdatetime(new Date());
            String s = DigestUtils.md5DigestAsHex((sysUser.getPassword() + sysUser.getSalt()).getBytes());
            sysUser.setPassword(s);
            this.sysUserMapper.insert(sysUser);
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserid(sysUser.getId());
            sysRoleUser.setRoleid(sysUser.getRoleId());
            this.sysRoleUserMapper.insert(sysRoleUser);
        }else {
            sysUser.setUpdatetime(new Date());
            String s = DigestUtils.md5DigestAsHex((sysUser.getPassword() + sysUser.getSalt()).getBytes());
            sysUser.setPassword(s);
            this.sysUserMapper.updateById(sysUser);

            //先删后新增
            QueryWrapper<SysRoleUser> sysRoleUserQueryWrapper = new QueryWrapper<>();
            sysRoleUserQueryWrapper.eq("userId", sysUser.getId());
            this.sysRoleUserMapper.delete(sysRoleUserQueryWrapper);

            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserid(sysUser.getId());
            sysRoleUser.setRoleid(sysUser.getRoleId());
            this.sysRoleUserMapper.insert(sysRoleUser);
        }
    }
}




